clear all
set more off
capture log close
set matsize 11000 

*---- Set Directory ----*
global rootDir = "/Users/AliceZhang/Dropbox/Research_Columbia/Renewables Voting (Urpelainen Zhang)/JOP/UZ_JOP2021_Replication"
global dataDir = "Data"
global resultDir = "Results"
global logDir = "Analysis/logSTATA"
global graphDir = "Results/Figures"

*---- Log File Path ----*
cd "$rootDir/$logDir"
log using 005_analysis_election, replace


*******************************************************************************
/*				          URPELAINEN & ZHANG 2021	        				 */
*******************************************************************************

/* 

File Name:    	005_analysis_election.do

By:				Alice Tianbo Zhang (alice.tianbo.zhang@gmail.com)

Last Edited:  	11/3/2021

Purpose:		

Data Used:      election_district_panel.dta
				ACS_panel_balanceTest_recodeVar.dta

Program Used:   - reghdfe -
				- plausexog - 

*/


*******************************************************************************
/*                     				TABLE 3						   		     */
*******************************************************************************

** Load election district panel
cd "$rootDir/$dataDir/Final"
use election_district_panel.dta, clear

** Create instrument and fixed effects
gen t = year - 2004
gen inter = t * mean_wp

egen stateyear_fixed = group(state year)
egen district_fixed = group(state district)

gen cum_lncapacity_turbine = log(cum_capacity_turbine + 1)
gen cum_lncount_turbine = log(cum_count_turbine +1 )

gen turnout = votes1 + votes2 + votes3 + votes4
gen lnturnout = log(turnout)

reghdfe incumbvotes (cum_capacity_turbine=inter), absorb(stateyear_fixed district_fixed) stages(first) vce(cluster district_fixed) old


*-------------- Create function iv_2sls to save REGHDFE outputs -------------*
local outcome demvotesmajorpercent repvotesmajorpercent incumbvotesmajorpercent turnout lnturnout // outcome variable 
local endogenous cum_capacity_turbine cum_count_turbine cum_lncapacity_turbine cum_lncount_turbine // endogenous variable
local instrument inter // instrument
local admin1_trend stateyear_fixed // geography * time trend
local admin2 district_fixed // panel unit (cluster variable)


foreach y in `outcome' {
	// Create outcome variable label for storing estimates
	local y_name = substr("`y'", 1, 3)
	
	foreach x in `endogenous' {
			// Create endogenous variable label for storing estimates
			tokenize "`x'", parse("_")
			local x_name "`3'"
			di "`x_name'"
			
			// Run IV regression
			reghdfe `y' (`x' = `instrument'), absorb(`admin1_trend' `admin2') ffirst stages(first ols reduced) vce(cluster `admin2') old
			
			// Store IV, first stage, OLS, reduced form estimates
			estimates store `y_name'_`x_name'_iv
			estimates restore reghdfe_first1
			estimates store `y_name'_`x_name'_first
			estimates restore reghdfe_ols
			estimates store `y_name'_`x_name'_ols
			estimates restore reghdfe_reduced
			estimates store `y_name'_`x_name'_reduced
		}
}


*-------------------- Export LaTeX tables - Main Results --------------------*
cd "$rootDir/$resultDir/Tables"

* OLS
esttab dem_capacity_ols dem_count_ols  ///
		inc_capacity_ols inc_count_ols using Table3.tex, booktabs replace ///
		refcat(cum_capacity_turbine "\emph{Panel A: OLS}", nolabel) ///
		b(%9.3f) se noconstant noobs nonotes star(* 0.10 ** 0.05 *** 0.01) ///
		varlabels(cum_capacity_turbine "Cumulative capacity (MW)" cum_count_turbine "Cumulative count") varwidth(27) modelwidth(13) ///
		mtitles("Model" "Model" "Model" "Model") ///
		mgroups("Democratic Vote" "Incumbent Vote", pattern(1 0 1 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) ///
		width(\hsize)
		
* IV
esttab dem_capacity_iv dem_count_iv ///
		inc_capacity_iv inc_count_iv using Table3.tex, booktabs append ///
		nomtitles se noconstant nonotes legend nonumbers collabels(none) star(* 0.10 ** 0.05 *** 0.01) ///
		b(%9.3f) stats(N N_clust r2, labels("Observations" "Districts" "\(R^{2}\)") fmt(0 0 2)) ///
		varlabels(cum_capacity_turbine "Cumulative capacity (MW)" cum_count_turbine "Cumulative count") varwidth(27) modelwidth(13) ///
		refcat(cum_capacity_turbine "\emph{Panel B: IV}", nolabel) ///
		width(\hsize)



*******************************************************************************
/*                     				TABLE 5						   		     */
*******************************************************************************

* OLS
esttab tur_capacity_ols tur_count_ols lnt_capacity_ols lnt_count_ols using Table5.tex, booktabs replace ///
		refcat(cum_capacity_turbine "\emph{Panel A: OLS}", nolabel) ///
		b(%9.3f) se noconstant noobs nonotes star(* 0.10 ** 0.05 *** 0.01) ///
		varlabels(cum_capacity_turbine "Cumulative capacity (MW)" cum_count_turbine "Cumulative count") varwidth(27) modelwidth(13) ///
		mtitles("Model" "Model" "Model" "Model") ///
		mgroups("Turnout" "log(Turnout)", pattern(1 0 1 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) ///
		width(\hsize)
		
* IV
esttab tur_capacity_iv tur_count_iv lnt_capacity_iv lnt_count_iv using Table5.tex, booktabs append ///
		nomtitles se noconstant nonotes legend nonumbers collabels(none) star(* 0.10 ** 0.05 *** 0.01) ///
		b(%9.3f) stats(N N_clust r2, labels("Observations" "Districts" "\(R^{2}\)") fmt(0 0 2)) ///
		varlabels(cum_capacity_turbine "Cumulative capacity (MW)" cum_count_turbine "Cumulative count") varwidth(27) modelwidth(13) ///
		refcat(cum_capacity_turbine "\emph{Panel B: IV}", nolabel) ///
		width(\hsize)


*******************************************************************************
/*           						TABLE 4	  							    */
*******************************************************************************
local outcome incumbvotesmajorpercent // outcome variable 
local endogenous cum_capacity_turbine cum_count_turbine cum_lncapacity_turbine cum_lncount_turbine // endogenous variable
local instrument inter // instrument
local admin1_trend stateyear_fixed // geography * time trend
local admin2 district_fixed // panel unit (cluster variable)
local party Dem Rep // party

foreach z in `party' {
	capture drop incumbent_`z'
	gen incumbent_`z' = 0
	replace incumbent_`z' = 1 if incumbent_party == "`z'"
				
	foreach y in `outcome' {
		// Create outcome variable label for storing estimates
		local y_name = substr("`y'", 1, 3)
		
		foreach x in `endogenous' {
				// Create endogenous variable label for storing estimates
				tokenize "`x'", parse("_")
				local x_name "`3'"
				di "`x_name'"
				
				// Run IV regression
				reghdfe `y' (`x' = `instrument') if incumbent_`z' == 1, absorb(`admin1_trend' `admin2') ffirst stages(first ols reduced) vce(cluster `admin2') old
				
				// Store IV, first stage, OLS, reduced form estimates
				estimates store `y_name'_`x_name'_`z'_iv
				estimates restore reghdfe_first1
				estimates store `y_name'_`x_name'_`z'_first
				estimates restore reghdfe_ols
				estimates store `y_name'_`x_name'_`z'_ols
				estimates restore reghdfe_reduced
				estimates store `y_name'_`x_name'_`z'_reduced
			}
	}
}

*------------ Export LaTeX regression tables - Heterogeneous Effects ---------*
cd "$rootDir/$resultDir/Tables"

** Compare OLS and IV estimates
* OLS
esttab inc_capacity_Dem_ols inc_count_Dem_ols inc_capacity_Rep_ols inc_count_Rep_ols using Table4.tex, booktabs replace ///
		refcat(cum_capacity_turbine "\emph{Panel A: OLS}", nolabel) ///
		b(%9.3f) se noconstant noobs nonotes star(* 0.10 ** 0.05 *** 0.01) ///
		varlabels(cum_capacity_turbine "Cumulative capacity (MW)" cum_count_turbine "Cumulative count") varwidth(27) modelwidth(13) ///
		mtitles("Model" "Model" "Model" "Model") ///
		mgroups("Democratic Incumbent" "Republican Incumbent", pattern(1 0 1 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) ///
		width(\hsize)
		
* IV
esttab inc_capacity_Dem_iv inc_count_Dem_iv inc_capacity_Rep_iv inc_count_Rep_iv using Table4.tex, booktabs append ///
		nomtitles se noconstant nonotes legend nonumbers collabels(none) star(* 0.10 ** 0.05 *** 0.01) ///
		b(%9.3f) stats(N N_clust r2, labels("Observations" "Districts" "\(R^{2}\)") fmt(0 0 2)) ///
		varlabels(cum_capacity_turbine "Cumulative capacity (MW)" cum_count_turbine "Cumulative count") varwidth(27) modelwidth(13) ///
		refcat(cum_capacity_turbine "\emph{Panel B: IV}", nolabel) ///
		width(\hsize)


		
*******************************************************************************
/*         	  						TABLE A8 						         */
*******************************************************************************
gen cali = 0
replace cali = 1 if state == "California"

local outcome demvotesmajorpercent repvotesmajorpercent incumbvotesmajorpercent // outcome variable 
local endogenous cum_capacity_turbine cum_count_turbine cum_lncapacity_turbine cum_lncount_turbine // endogenous variable
local instrument inter // instrument
local admin1_trend stateyear_fixed // geography * time trend
local admin2 district_fixed // panel unit (cluster variable)

foreach y in `outcome' {
	// Create outcome variable label for storing estimates
	local y_name = substr("`y'", 1, 3)
	
	foreach x in `endogenous' {
			// Create endogenous variable label for storing estimates
			tokenize "`x'", parse("_")
			local x_name "`3'"
			di "`x_name'"
			
			// Run IV regression
			reghdfe `y' (`x' = `instrument') if cali == 0, absorb(`admin1_trend' `admin2') ffirst stages(first ols reduced) vce(cluster `admin2') old
			
			// Store IV, first stage, OLS, reduced form estimates
			estimates store `y_name'_`x_name'_iv_noCA
			estimates restore reghdfe_first1
			estimates store `y_name'_`x_name'_first_noCA
			estimates restore reghdfe_ols
			estimates store `y_name'_`x_name'_ols_noCA
			estimates restore reghdfe_reduced
			estimates store `y_name'_`x_name'_reduced_noCA
		}
}


*-------------------- Export LaTeX tables - Drop California --------------------*
cd "$rootDir/$resultDir/Tables"
		
** Compare OLS and IV estimates
* OLS
esttab dem_capacity_ols_noCA dem_count_ols_noCA rep_capacity_ols_noCA rep_count_ols_noCA ///
		inc_capacity_ols_noCA inc_count_ols_noCA using TableA8.tex, booktabs replace ///
		refcat(cum_capacity_turbine "\emph{Panel A: OLS}", nolabel) ///
		b(%9.3f) se noconstant noobs nonotes star(* 0.10 ** 0.05 *** 0.01) ///
		varlabels(cum_capacity_turbine "Cumulative capacity (MW)" cum_count_turbine "Cumulative count") varwidth(27) modelwidth(13) ///
		mtitles("Model" "Model" "Model" "Model" "Model" "Model") ///
		mgroups("Democratic Vote" "Republican Vote" "Incumbent Vote", pattern(1 0 1 0 1 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) ///
		width(\hsize)
		
* IV
esttab dem_capacity_iv_noCA dem_count_iv_noCA rep_capacity_iv_noCA rep_count_iv_noCA ///
		inc_capacity_iv_noCA inc_count_iv_noCA using TableA8.tex, booktabs append ///
		nomtitles se noconstant nonotes legend nonumbers collabels(none) star(* 0.10 ** 0.05 *** 0.01) ///
		b(%9.3f) stats(N N_clust r2, labels("Observations" "Districts" "\(R^{2}\)") fmt(0 0 2)) ///
		varlabels(cum_capacity_turbine "Cumulative capacity (MW)" cum_count_turbine "Cumulative count") varwidth(27) modelwidth(13) ///
		refcat(cum_capacity_turbine "\emph{Panel B: IV}", nolabel) ///
		width(\hsize)


*******************************************************************************
/*         	 					   TABLE A14								 */
*******************************************************************************
cd "$rootDir/$dataDir/Final"
use ACS_panel_balanceTest_recodeVar.dta, clear

** Merge w/t election period panel
drop cum_count_turbine-GEOid2 
merge 1:1 state district year using election_district_panel.dta, update
keep if _merge == 3

** Create instrument and fixed effects
gen t = year - 2003
gen inter = t * mean_wp

egen stateyear_fixed = group(state year)
egen district_fixed = group(state district)

gen cum_lncapacity_turbine = log(cum_capacity_turbine + 1)
gen cum_lncount_turbine = log(cum_count_turbine +1 )


** Include balance variable as controls
** incumbent
reghdfe incumbvotes pop white home_median (cum_capacity_turbine=inter), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store inc_capacityB_iv

reghdfe incumbvotes pop white home_median (cum_count_turbine=inter), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store inc_countB_iv

** dem
reghdfe demvotesmajor pop white home_median (cum_capacity_turbine=inter), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store dem_capacityB_iv

reghdfe demvotesmajor pop white home_median (cum_count_turbine=inter), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store dem_countB_iv

** rep
reghdfe repvotesmajor pop white home_median (cum_capacity_turbine=inter), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store rep_capacityB_iv

reghdfe repvotesmajor pop white home_median (cum_count_turbine=inter), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store rep_countB_iv


*--------------------- Export LaTeX regression tables -----------------------*
cd "$rootDir/$resultDir/Tables"

** IV estimates only
esttab dem_capacityB_iv dem_countB_iv rep_capacityB_iv rep_countB_iv ///
		inc_capacityB_iv inc_countB_iv using TableA14.tex, booktabs replace ///
		refcat(cum_capacity_turbine "\emph{Panel: IV}", nolabel) ///
		b(%9.3f) se noconstant nonotes legend star(* 0.10 ** 0.05 *** 0.01) ///
		varlabels(cum_capacity_turbine "Cumulative capacity (MW)" cum_count_turbine "Cumulative count" pop "Total population (thousand)" white "White (\%)" home_median "Median gross rent (\textdollar)",  ///
		elist(cum_capacity_turbine \addlinespace  cum_count_turbine \addlinespace  pop \addlinespace  white \addlinespace)) ///
		varwidth(27) modelwidth(13) order(cum_capacity_turbine cum_count_turbine pop white home_median)  ///
		stats(N N_clust r2, labels("Observations" "Districts" "\(R^{2}\)") fmt(0 0 2)) ///
		mtitles("Model" "Model" "Model" "Model" "Model" "Model") ///
		mgroups("Democratic Vote" "Republican Vote" "Incumbent Vote", pattern(1 0 1 0 1 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) ///
		width(\hsize)


*******************************************************************************
/*        							TABLE A16					 			*/
*******************************************************************************

** Load election district panel
cd "$rootDir/$dataDir/Final"
use election_district_panel.dta, clear

** Create instrument and fixed effects
gen t = year - 2004
gen inter_median = t * median_wp
gen inter_max = t * max_wp

egen stateyear_fixed = group(state year)
egen district_fixed = group(state district)

** Compare median and max zonal wind potential as IV
foreach var in median max {

* incumbent
reghdfe incumbvotes (cum_capacity_turbine=inter_`var'), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store inc_capacity_`var'_iv

reghdfe incumbvotes (cum_count_turbine=inter_`var'), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store inc_count_`var'_iv

** dem
reghdfe demvotesmajor (cum_capacity_turbine=inter_`var'), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store dem_capacity_`var'_iv

reghdfe demvotesmajor (cum_count_turbine=inter_`var'), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store dem_count_`var'_iv

** rep
reghdfe repvotesmajor (cum_capacity_turbine=inter_`var'), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store rep_capacity_`var'_iv

reghdfe repvotesmajor (cum_count_turbine=inter_`var'), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store rep_count_`var'_iv
}


*--------------------- Export LaTeX regression tables -----------------------*
cd "$rootDir/$resultDir/Tables"

** Median
esttab dem_capacity_median_iv dem_count_median_iv rep_capacity_median_iv rep_count_median_iv ///
		inc_capacity_median_iv inc_count_median_iv using TableA16.tex, booktabs replace ///
		refcat(cum_capacity_turbine "\emph{IV: Median}", nolabel) ///
		b(%9.3f) se noconstant noobs nonotes star(* 0.10 ** 0.05 *** 0.01) ///
		varlabels(cum_capacity_turbine "Cumulative capacity (MW)" cum_count_turbine "Cumulative count") varwidth(27) modelwidth(13) ///
		mtitles("Model" "Model" "Model" "Model" "Model" "Model") ///
		mgroups("Democratic Vote" "Republican Vote" "Incumbent Vote", pattern(1 0 1 0 1 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) ///
		width(\hsize)

** Max
esttab dem_capacity_max_iv dem_count_max_iv rep_capacity_max_iv rep_count_max_iv ///
		inc_capacity_max_iv inc_count_max_iv using TableA16.tex, booktabs append ///
		nomtitles se noconstant nonotes legend nonumbers collabels(none) star(* 0.10 ** 0.05 *** 0.01) ///
		b(%9.3f) stats(N N_clust r2, labels("Observations" "Districts" "\(R^{2}\)") fmt(0 0 2)) ///
		varlabels(cum_capacity_turbine "Cumulative capacity (MW)" cum_count_turbine "Cumulative count") varwidth(35) modelwidth(13) ///
		refcat(cum_capacity_turbine "\emph{IV: Maximum}", nolabel) ///
		width(\hsize)
		
		
*******************************************************************************
/*        							FIGURE A3								 */
*******************************************************************************

** Load election district panel
clear
cd "$rootDir/$dataDir/Final"
use election_district_panel.dta, clear

** Create instrument and fixed effects
gen t = year - 2004
gen inter = t * mean_wp

egen stateyear_fixed = group(state year)
egen district_fixed = group(state district)

tab stateyear_fixed, gen(d_sy)
tab district_fixed, gen(d_dist)


** Check theoretic bounds of gamma
foreach y in dem rep incumb {
	foreach x in capacity count {
		regress `y'votesmajorpercent d_sy* d_dist* inter cum_`x'_turbine, vce(cluster district_fixed) 
	}
}

* Note: Coefficients on inter are around -1.0 and +0.8


** Dem
plausexog uci demvotesmajorpercent d_sy* d_dist* (cum_capacity_turbine = inter), ///
				vce(cluster district_fixed) gmin(-1) gmax(1) graph(cum_capacity_turbine) level(0.95) ///
			    yline(0) title("Democratic Vote") xtitle("Delta") ytitle("Cumulative Capacity (MW)", size(small)) name(dem_capacity, replace) ///
				scheme(myplain) legend(pos(6) row(1) label(1 "Upper Bound (UCI)") label(2 "Lower Bound (UCI)"))

plausexog uci demvotesmajorpercent d_sy* d_dist* (cum_count_turbine = inter), ///
				vce(cluster district_fixed) gmin(-1) gmax(1) graph(cum_count_turbine) level(0.95) ///
				yline(0) title("Democratic Vote") xtitle("Delta") ytitle("Cumulative Count", size(small)) name(dem_count, replace) ///
				scheme(myplain) legend(pos(6) row(1) label(1 "Upper Bound (UCI)") label(2 "Lower Bound (UCI)"))

** Rep
plausexog uci repvotesmajorpercent d_sy* d_dist* (cum_capacity_turbine = inter), ///
				vce(cluster district_fixed) gmin(-1) gmax(1) graph(cum_capacity_turbine) level(0.95) ///
				yline(0) title("Republican Vote") xtitle("Delta") ytitle("Cumulative Capacity (MW)", size(small)) name(rep_capacity, replace) ///
				scheme(myplain) legend(pos(6) row(1) label(1 "Upper Bound (UCI)") label(2 "Lower Bound (UCI)"))

plausexog uci repvotesmajorpercent d_sy* d_dist* (cum_count_turbine = inter), ///
				vce(cluster district_fixed) gmin(-1) gmax(1) graph(cum_count_turbine) level(0.95) ///
				yline(0) title("Republican Vote") xtitle("Delta") ytitle("Cumulative Count", size(small)) name(rep_count, replace) ///
				scheme(myplain) legend(pos(6) row(1) label(1 "Upper Bound (UCI)") label(2 "Lower Bound (UCI)"))


** Inc
plausexog uci incumbvotesmajorpercent d_sy* d_dist* (cum_capacity_turbine = inter), ///
				vce(cluster district_fixed) gmin(-1) gmax(1) graph(cum_capacity_turbine) level(0.95) ///
			    yline(0) title("Incumbent Vote") xtitle("Delta") ytitle("Cumulative Capacity (MW)", size(small)) name(inc_capacity, replace) ///
				scheme(myplain) legend(pos(6) row(1) label(1 "Upper Bound (UCI)") label(2 "Lower Bound (UCI)"))

plausexog uci incumbvotesmajorpercent d_sy* d_dist* (cum_count_turbine = inter), ///
				vce(cluster district_fixed) gmin(-1) gmax(1) graph(cum_count_turbine) level(0.95) ///
				yline(0) title("Incumbent Vote") xtitle("Delta") ytitle("Cumulative Count", size(small)) name(inc_count, replace) ///
				scheme(myplain) legend(pos(6) row(1) label(1 "Upper Bound (UCI)") label(2 "Lower Bound (UCI)"))

				
grc1leg dem_capacity dem_count rep_capacity rep_count inc_capacity inc_count, legendfrom(dem_count) graphregion(color(white)) ///
		note("Union of confidence interval approach described in Conley et al.(2012)") rows(3) cols(2) ysize(5) xsize(20)

		
** Export graphs
cd "$rootDir/$graphDir" 
local i = 1
foreach y in dem rep inc {
	foreach x in capacity count {
	local j: word `i' of `c(alpha)'
			graph export fgA3`j'.pdf, name(`y'_`x') replace
			local i = `i' + 1
	}
}

*******************************************************************************
/*             					  TABLE A12-13				     		     */
*******************************************************************************
cd "$rootDir/$dataDir/Final"

** Load election district panel
use election_district_panel.dta, clear

** Create instrument and fixed effects
gen t = year - 2004
gen inter = t * mean_wp

egen stateyear_fixed = group(state year)
egen district_fixed = group(state district)
egen state_fixed = group(state)

gen cum_lncapacity_turbine = log(cum_capacity_turbine + 1)
gen cum_lncount_turbine = log(cum_count_turbine +1 )


*--------------------- Cluster Standard Error by State -----------------------*
local outcome demvotesmajorpercent repvotesmajorpercent incumbvotesmajorpercent // outcome variable 
local endogenous cum_capacity_turbine cum_count_turbine cum_lncapacity_turbine cum_lncount_turbine // endogenous variable
local instrument inter // instrument
local admin1_trend stateyear_fixed // geography * time trend
local admin2 district_fixed // panel unit (cluster variable)
local admin3 state_fixed // robustness: state fixed effects	
			
foreach y in `outcome' {
	// Create outcome variable label for storing estimates
	local y_name = substr("`y'", 1, 3)
	
	foreach x in `endogenous' {
			// Create endogenous variable label for storing estimates
			tokenize "`x'", parse("_")
			local x_name "`3'"
			di "`x_name'"
			
			// Run IV regression
			reghdfe `y' (`x' = `instrument'), absorb(`admin1_trend' `admin2') ffirst stages(first ols reduced) vce(cluster state_fixed) old
			
			// Store IV, first stage, OLS, reduced form estimates
			estimates store `y_name'_`x_name'_iv
			estimates restore reghdfe_first1
			estimates store `y_name'_`x_name'_first
			estimates restore reghdfe_ols
			estimates store `y_name'_`x_name'_ols
			estimates restore reghdfe_reduced
			estimates store `y_name'_`x_name'_reduced
		}
}


*--------------------- Export LaTeX regression tables -----------------------*
cd "$rootDir/$resultDir/Tables"

** Compare OLS and IV estimates
* OLS
esttab dem_capacity_ols dem_count_ols rep_capacity_ols rep_count_ols ///
		inc_capacity_ols inc_count_ols using TableA12.tex, booktabs replace ///
		refcat(cum_capacity_turbine "\emph{Panel A: OLS}", nolabel) ///
		b(%9.3f) se noconstant noobs nonotes star(* 0.10 ** 0.05 *** 0.01) ///
		varlabels(cum_capacity_turbine "Cumulative capacity (MW)" cum_count_turbine "Cumulative count") varwidth(27) modelwidth(13) ///
		mtitles("Model" "Model" "Model" "Model" "Model" "Model") ///
		mgroups("Democratic Vote" "Republican Vote" "Incumbent Vote", pattern(1 0 1 0 1 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) ///
		width(\hsize)
		
* IV
esttab dem_capacity_iv dem_count_iv rep_capacity_iv rep_count_iv ///
		inc_capacity_iv inc_count_iv using TableA12.tex, booktabs append ///
		nomtitles se noconstant nonotes legend nonumbers collabels(none) star(* 0.10 ** 0.05 *** 0.01) ///
		b(%9.3f) stats(N N_clust r2, labels("Observations" "States" "\(R^{2}\)") fmt(0 0 2)) ///
		varlabels(cum_capacity_turbine "Cumulative capacity (MW)" cum_count_turbine "Cumulative count") varwidth(27) modelwidth(13) ///
		refcat(cum_capacity_turbine "\emph{Panel B: IV}", nolabel) ///
		width(\hsize)

		
*------------------ Table A13: Bootstrap Standard Errors ---------------------*
set seed 12345

local outcome demvotesmajorpercent repvotesmajorpercent incumbvotesmajorpercent // outcome variable 
local endogenous cum_capacity_turbine cum_count_turbine // endogenous variable
local instrument inter // instrument
local admin1_trend stateyear_fixed // geography * time trend
local admin2 district_fixed // panel unit (cluster variable)
local admin3 state_fixed // robustness: state fixed effects	
			
foreach y in `outcome' {
	// Create outcome variable label for storing estimates
	local y_name = substr("`y'", 1, 3)
	
	foreach x in `endogenous' {
			// Create endogenous variable label for storing estimates
			tokenize "`x'", parse("_")
			local x_name "`3'"
			di "`x_name'"
			
			// Run IV regression
			reghdfe `y' i.stateyear_fixed (`x' = `instrument'), absorb(`admin2') vce(cluster state_fixed) old
			
			// Store IV estimates
			estimates store `y_name'_`x_name'_iv
			
			boottest `x', ptype(equaltail)
		}
}

		
*******************************************************************************
/*       					      TABLE A18 							     */
*******************************************************************************
cd "$rootDir/$dataDir/Final"

** Load election district panel
use election_district_panel.dta, clear


** Calculate national wind turbine installation by year
preserve
collapse (sum) count_turbine capacity_turbine, by(year)
rename count_turbine us_count_turbine
rename capacity_turbine us_capacity_turbine
tempfile sum_year_turbines
save `sum_year_turbines' 
restore


** Merge w/t panel 
capture drop _merge
merge m:1 year using `sum_year_turbines' 
order us_count_turbine us_capacity_turbine, before(count_turbine)

** Create instrument and fixed effects
gen t = year - 2004
gen inter = t * mean_wp
gen bartik_iv_capacity = us_capacity_turbine * mean_wp
gen bartik_iv_count = us_count_turbine * mean_wp

egen stateyear_fixed = group(state year)
egen district_fixed = group(state district)
egen state_fixed = group(state)

gen cum_lncapacity_turbine = log(cum_capacity_turbine + 1)
gen cum_lncount_turbine = log(cum_count_turbine +1 )


foreach var in capacity count {

* incumbent
reghdfe incumbvotes (cum_capacity_turbine=bartik_iv_`var'), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store inc_capacity_b`var'

reghdfe incumbvotes (cum_count_turbine=bartik_iv_`var'), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store inc_count_b`var'

** dem
reghdfe demvotesmajor (cum_capacity_turbine=bartik_iv_`var'), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store dem_capacity_b`var'

reghdfe demvotesmajor (cum_count_turbine=bartik_iv_`var'), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store dem_count_b`var'

** rep
reghdfe repvotesmajor (cum_capacity_turbine=bartik_iv_`var'), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store rep_capacity_b`var'

reghdfe repvotesmajor (cum_count_turbine=bartik_iv_`var'), absorb(stateyear_fixed district_fixed) vce(cluster district_fixed) old
estimates store rep_count_b`var'
}


*--------------------- Export LaTeX regression tables -----------------------*
cd "$rootDir/$resultDir/Tables"

** Bartik - National Installed Wind Capacity
esttab dem_capacity_bcapacity dem_count_bcapacity ///
		rep_capacity_bcapacity rep_count_bcapacity ///
		inc_capacity_bcapacity inc_count_bcapacity ///
		using TableA18.tex, booktabs replace ///
		refcat(cum_capacity_turbine "\emph{IV: Mean wind potential * National wind capacity}", nolabel) ///
		se noconstant nonotes legend nonumbers collabels(none) star(* 0.10 ** 0.05 *** 0.01) ///
		b(%9.3f) stats(N N_clust r2, labels("Observations" "States" "\(R^{2}\)") fmt(0 0 2)) ///
		varlabels(cum_capacity_turbine "Cumulative capacity (MW)" cum_count_turbine "Cumulative count") varwidth(27) modelwidth(13) ///
		mtitles("Model" "Model" "Model" "Model" "Model" "Model") ///
		mgroups("Democratic Vote" "Republican Vote" "Incumbent Vote", pattern(1 0 1 0 1 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) ///
		width(\hsize)

		

** Close log file
log close
cd "$rootDir/$logDir"
translate 005_analysis_election.smcl 005_analysis_election.log, replace

